import React, { useEffect, useState, useContext } from 'react'
import MyContent from '@/store/my-context'
import styles from './index.less'
import moment from "moment"
import IconFont from "@/components/iconfont"
import { getSongdetailByids } from '@/api'
import {dispatchType,sourceType} from '@/interfaces/types'
import { setPlayIndexInList, addNewPlayId } from '@/store/functions'
interface bottomType {
  btnShoucangIsDisplay: boolean
}
moment.locale('zh-cn')
const Bottompage: React.FC<bottomType> = ({ btnShoucangIsDisplay}) => {
  const { dispatch, state } = useContext(MyContent);
  const [totalCount, setTotalCount] = useState<number>(0)
  const [hisTotalCount,setHisTotalCount] = useState<number>(0)
  const [clickedLast, setClickedLast] = useState<number>(-1)
  const [playingId, setPlayingId] = useState<number>(-1)
  const [songsDetail, setSongsDetail] = useState<Array<Object>>([])
  const [songsHisDetail,setSongsHisDetail] = useState<Array<any>>([])
  useEffect(() => {
      let info = state.songsInfoHis
      let thisIds: Array<number> = info.map((res: { id: number }) => {
        return res.id
      })
      if (thisIds?.length > 0) {
        setHisTotalCount(thisIds.length)
        getSongdetailByids({ ids: thisIds.join(',') }).then(res => {
          setSongsHisDetail(res?.songs)
        }).catch(err => console.log(err))
      } else {
        setSongsHisDetail([])
        setHisTotalCount(0)
      }
  }, [state.sIHC])
  useEffect(()=>{
    setClickedLast(-1)//歌单变化后清除点击留下样式
  },[btnShoucangIsDisplay])
  useEffect(() => {
      let thisIds: Array<number> = state.songsInfoPlay.map((res: { id: number }) => {
        return res.id
      })
      if (thisIds?.length > 0) {
        setTotalCount(thisIds.length)
        getSongdetailByids({ ids: thisIds.join(',') }).then(res => {
          setSongsDetail(res?.songs)
        }).catch(err => console.log(err))
      } else {
        setTotalCount(0)
        setSongsDetail([])
      }
  }, [state.sIPC])
  useEffect(() => {
    if (state?.playInfo?.playingId > 0) {
      setPlayingId(state?.playInfo?.playingId)
    }
  }, [state?.playInfo?.playingId])
  const selectionsSeparate = '|'
  const deleteFunction = () => {
    if (btnShoucangIsDisplay) {
      dispatch({ type: "DELETE_ALL" })
    } else {
      dispatch({ type: "DELETE_HIS" })
    }
  }
  const toPlayHis = (tid: number, tsource: sourceType) => {
    addNewPlayId(tid, tsource, state).then((res: dispatchType | null) => {
      if (res) {
        dispatch(res)
      }
    }).catch((err: any) => {
      console.log(err);
    })
  }
  const toPlayList = (tindex: number) => {
    setPlayIndexInList(tindex, state).then((res: dispatchType | null) => {
      if (res) {
        dispatch(res)
      }
    }).catch((err: any) => {
      console.log(err);
    })
  }
  return (
    <div className={styles["bottompage"]} > {/* onLoad={onLoad()}  页面还没加载，onload已经渲染很多次*/}
      <div className={styles["linetop"]}>
        <span className={styles['totalcount']}>
          共{btnShoucangIsDisplay ? totalCount:hisTotalCount}首
        </span>
        <div className={styles['btns']}>
          <a className={styles["btn-left"]} style={btnShoucangIsDisplay
            ? {} : { display: 'none' }
          }>
            <IconFont type='iconshoucang' />
            收藏全部
          </a>
          <span className={styles['separate']} style={btnShoucangIsDisplay
            ? {} : { display: 'none' }
          }>
            {selectionsSeparate}
          </span>
          <a className={styles["btn-right"]} onClick={() => deleteFunction()}>
            <IconFont type='iconshanchu' />
          清空
          </a>
        </div>

      </div>
      <div 
      className={styles['songlist-container']}
      style={btnShoucangIsDisplay?{}:{display:'none'}}>
      { songsDetail?.length > 0 ?
        (songsDetail?.map((song: any, index: number) => (
          <div key={song?.id}
            className={styles["songlist"]}
            style={clickedLast === index ? { backgroundColor: 'rgb(229,229,229)' } : {}}
            onClick={() => {
              setClickedLast(index)
            }}
            onDoubleClick={() => {
                toPlayList(index)
            }}
          >
            <span className={styles['icon-play-pause']}>
              <IconFont style={playingId && playingId === song?.id
                ? { color: 'rgb(239,94,94)' } : { display: 'none' }}
                type={state.playInfo.isPlay ? 'iconbofang' : 'iconzanting'} />
            </span>
            <span className={styles['songlist-name']}
              style={playingId && playingId === song?.id
                ? { color: 'rgb(238,89,89)' } : {}}>
              {song.name}
            </span>
            <a className={styles['songlist-artist']}
              style={playingId && playingId === song?.id
                ? { color: 'rgb(236,65,65)' } : {}}>
              {song.ar.length < 2
                ? song.ar[0].name
                : song.ar[0].name + "/" + song.ar[1].name}
            </a>
            <a className={styles['songlist-href']}>
              <IconFont type='iconlianjie' />
            </a>
            <span className={styles['songlist-playtime']}>
              { moment(song.dt).format("mm:ss")
              }
            </span>
          </div>
        )))
        : (<div>
          <p style={{
            marginTop: '20%', fontSize: '18px',
            display: 'block', textAlign: 'center', color: 'rgb(153,153,153)'
          }}>
            你还没有添加音乐
            </p>
          <a  style={{
            marginTop: '5%',
            textDecoration: 'underline', color: 'rgb(51,51,51)',
            display: 'block', fontSize: '14px', textAlign: 'center'
          }}>
            去首页发现音乐
            </a>
        </div>)
      }
      </div>
      <div className={styles['songlist-container']} style={btnShoucangIsDisplay?{display:'none'}:{}}>
      { songsHisDetail?.length > 0 ?
        (songsHisDetail?.map((song: any, index: number) => (
          <div key={song?.id}
            className={styles["songlist"]}
            style={clickedLast === index ? { backgroundColor: 'rgb(229,229,229)' } : {}}
            onClick={() => {
              setClickedLast(index)
            }}
            onDoubleClick={() => {
                toPlayHis(song?.id, state.songsInfoHis[index].source)
            }}
          >
            <span className={styles['icon-play-pause']}>
              <IconFont style={playingId && playingId === song?.id
                ? { color: 'rgb(239,94,94)' } : { display: 'none' }}
                type={state.playInfo.isPlay ? 'iconbofang' : 'iconzanting'} />
            </span>
            <span className={styles['songlist-name']}
              style={playingId && playingId === song?.id
                ? { color: 'rgb(238,89,89)' } : {}}>
              {song.name}
            </span>
            <a className={styles['songlist-artist']}
              style={playingId && playingId === song?.id
                ? { color: 'rgb(236,65,65)' } : {}}>
              {song.ar.length < 2
                ? song.ar[0].name
                : song.ar[0].name + "/" + song.ar[1].name}
            </a>
            <a className={styles['songlist-href']}>
              <IconFont type='iconlianjie' />
            </a>
            <span className={styles['songlist-playtime']}>
              {moment(state?.songsInfoHis[index]?.playTimeMS).fromNow()
              }
            </span>
          </div>
        )))
        : (<div>
          <p style={{
            marginTop: '20%', fontSize: '18px',
            display: 'block', textAlign: 'center', color: 'rgb(153,153,153)'
          }}>
            你还没有播放过音乐
            </p>
          <a style={{
            marginTop: '5%',
            textDecoration: 'underline', color: 'rgb(51,51,51)',
            display: 'block', fontSize: '14px', textAlign: 'center'
          }}>
            去首页发现音乐
            </a>
        </div>)
      }
      </div>
    </div>
  );
}
const SonglistForPlay: React.FC<any> = () => {
  const { state } = useContext(MyContent)
  const [tabName, setTabName] = useState('first')
  return (
    <div className={styles['page']} style={state.showList ? {} : { visibility:'hidden' }}
      onClick={(event) => {
        event.stopPropagation()
      }}>
      <ul className={styles['topselection']}>
        <li>
          <input type='button' value='播放列表' onClick={() => setTabName('first')}
            className={`${`${tabName}` === `${'first'}` ? {} : `${styles['unselected']}`}`} />
          <input type='button' value='历史记录' onClick={() => setTabName('second')}
            className={`${`${tabName}` === `${'second'}` ? {} : `${styles['unselected']}`}`} />
        </li>
      </ul>
      {/* <Spin tip="加载中..." spinning={isLoading}> */}
        <Bottompage btnShoucangIsDisplay={tabName === 'first'}/>
      {/* </Spin> */}
    </div>
  )
}
export default SonglistForPlay
